﻿using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections;
using System.Threading.Tasks;

namespace RecognitionForm
{
    public class MsgHub : Hub
    {
        private readonly static ConnectionMapping<string> _connections = new ConnectionMapping<string>();

        public void Send(string content)
        {
            //string name = Context.QueryString["name"];

            Console.WriteLine("服务器中转内容：" + content);
            //通知所有客户端  
            Clients.All.receive(content);
        }

        public void SendPrivateMessage(string who, string message)
        {
            string name = Context.QueryString["name"];

            foreach (var connectionId in _connections.GetConnections(who))
            {
                Clients.Client(connectionId).receive(message);
                //Clients.Client(connectionId).receive(name + ": " + message);
            }
        }

        public override Task OnConnected()
        {
            string name = Context.QueryString["name"];

            _connections.Add(name, Context.ConnectionId);

            return base.OnConnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            string name = Context.QueryString["name"];

            _connections.Remove(name, Context.ConnectionId);

            return base.OnDisconnected(stopCalled);
        }
    }
}
